﻿using System.Security.Claims;
using ApiLib.AppStart;
using ApiLib.Helpers;
using ApiLib.Models;
using Furion;
using Furion.Authorization;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;

namespace ApiLib.Common;

/// <summary>
/// JWT处理，认证授权
/// </summary>
public class JwtHandler : AppAuthorizeHandler
{
    /// <summary>
    /// 
    /// </summary>
    /// <param name="context"></param>
    /// <param name="httpContext"></param>
    /// <returns></returns>
    public override Task<bool> PipelineAsync(AuthorizationHandlerContext context, DefaultHttpContext httpContext)
    {
        /*var uuid = App.User.FindFirstValue(ClaimTypes.UserData);
        if (!string.IsNullOrEmpty(uuid))
        {
            App.User.AddIdentity(new ClaimsIdentity(new[]
            {
                new Claim(ClaimTypes.Authentication, uuid)
            }));
        }*/
        /*// 这里写您的授权判断逻辑，授权通过返回 true，否则返回 false
        var sid = App.User.FindFirstValue(ClaimTypes.Sid);
        if (sid != null && int.TryParse(sid, out var id) && id > 0)
        {
            var authStr = httpContext.Request.Headers.Authorization.ToString() ?? "";
            var token = authStr.Replace("Bearer ", "");
            // var sysUserinfo = DbHelper.Db.Queryable<SysUserinfo>().InSingle(id);
            var baseUser = GlobalConfig.BaseAuthorization?.Authorization(token);
            if (baseUser == null)
            {
                baseUser = GlobalConfig.BaseAuthorization?.GetUser(sid);
                if (baseUser is SysUserinfo sysUserinfo)
                {
                    sysUserinfo.InitPermissions();
                    DbHelper.SetUserCache(token, sysUserinfo);
                }
            }

            App.User.AddIdentity(new ClaimsIdentity(new[]
            {
                // new Claim(ClaimTypes.Role, sysUserinfo.Role ?? ""),
                // new Claim(ClaimTypes.UserData, sysUserinfo.Permissions ?? ""),
                new Claim(ClaimTypes.Authentication, token)
            }));
        }*/

        return Task.FromResult(true);
    }
}